// src/utils/storage.ts

type StorageValue = string | number | boolean | object | null
interface StorageData {
  expire: number
  value: StorageValue
}

class Cache {
  // 缓存前缀
  private static keyPrev: string = 'store_'

  // 获取带前缀的完整键名
  private static getKey(key: string): string {
    return `${this.keyPrev}${key}`
  }

  // 获取当前时间戳（单位：秒）
  static time(): number {
    return Math.round(Date.now() / 1000)
  }

  /**
   * 设置缓存
   * @param key 缓存键
   * @param value 缓存值
   * @param expire 过期时间（单位：秒）
   */
  static set(key: string, value: StorageValue, expire?: number): boolean {
    const data: StorageData = {
      value,
      expire: expire ? this.time() + expire : 0
    }

    try {
      uni.setStorageSync(this.getKey(key), JSON.stringify(data))
      return true
    } catch (e) {
      console.error('Storage set error:', e)
      return false
    }
  }

  /**
   * 获取缓存
   * @param key 缓存键
   * @returns 缓存值或 false（过期/不存在）
   */
  static get(key: string): StorageValue | false {
    try {
      const storedData = uni.getStorageSync(this.getKey(key))
      if (!storedData) return false

      const { value, expire } = JSON.parse(storedData) as StorageData
      
      // 检查过期时间
      if (expire && expire < this.time()) {
        this.remove(key)
        return false
      }
      
      return value
    } catch (e) {
      console.error('Storage get error:', e)
      return false
    }
  }

  /**
   * 移除指定缓存
   * @param key 缓存键
   */
  static remove(key: string): void {
    uni.removeStorageSync(this.getKey(key))
  }

  /**
   * 清空所有带前缀的缓存
   */
  static clearAll(): void {
    const keys = uni.getStorageInfoSync().keys
    keys
      .filter(key => key.startsWith(this.keyPrev))
      .forEach(key => uni.removeStorageSync(key))
  }
}

export default Cache